using System.IO;
using System.CodeDom.Compiler;

using HuaXianQu.ProtoBuffEx.Runtime;
using Microsoft.CSharp;
using Assembly = System.Reflection.Assembly;

namespace HuaXianQu.ProtoBuffEx.ToolEditor
{
    public class ProtoDllTool
    {
        
        string protoDllPath =>
            Path.GetFullPath($"{ProtoPathConfig.Inst.GenerateProtoDllPath}/{ProtoPathConfig.Inst.ProtoDllName}.dll");

        public void CompileToDll()
        {
            // 设置 C# 文件夹路径和输出 DLL 文件路径
            string scriptFolderPath =
                $"{ProtoPathConfig.Inst.PackagesPath}/Runtime/ProtoInterface"; // 输入你的 C# 脚本所在文件夹路径
            string protoInterfaceDllPath =
                Path.GetFullPath(
                    $"{ProtoPathConfig.Inst.GenerateCsCachePath}/{ProtoBuffPackageConfig.ProtoInterface}.dll");
            CompileToDll(protoInterfaceDllPath, scriptFolderPath, new[] { "System" });
            CompileToDll(protoDllPath, ProtoPathConfig.Inst.GenerateProtoCsRootPath,
                new[] { "System", ProtoPathConfig.Inst.GoogleProtobufPath, protoInterfaceDllPath });
        }

        public void CompileToDll(string dllPath, string scriptFolderPath, string[] compilerList)
        {
            // 获取所有 C# 文件路径
            string[] scriptPaths = Directory.GetFiles(scriptFolderPath, "*.cs", SearchOption.AllDirectories);

            if (scriptPaths.Length == 0)
            {
                ProtoDebug.LogError($"路径：{scriptFolderPath}没有找到 C# 脚本文件！");
                return;
            }

            //Debug.Log("找到 " + scriptPaths.Length + " 个 C# 脚本文件。");


            // 创建编译器实例
            var csharpCompiler = new CSharpCodeProvider();
            var compilerParams = new CompilerParameters
            {
                GenerateExecutable = false,
                OutputAssembly = dllPath,
            };
            compilerParams.ReferencedAssemblies.AddRange(compilerList);
            string dirPath = Path.GetDirectoryName(dllPath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            // 编译所有 C# 文件
            var results = csharpCompiler.CompileAssemblyFromFile(compilerParams, scriptPaths);

            // 检查编译结果
            if (results.Errors.Count > 0)
            {
                ProtoDebug.LogError("编译失败：");
                foreach (CompilerError error in results.Errors)
                {
                    ProtoDebug.LogError(error.ErrorText);
                }
            }
            // else
            // {
            //     ProtoDebug.Log("编译成功，DLL 输出路径：" + dllPath);
            // }
        }

        public Assembly GetProtoBuffAssembly()
        {
            return Assembly.LoadFrom(protoDllPath);
        }
    }
}